package com.campus.counseling.config;

import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;

@Configuration
@EnableWebSocketMessageBroker
@RequiredArgsConstructor
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    private final WebSocketAuthInterceptor webSocketAuthInterceptor;
    private static final Logger log = LoggerFactory.getLogger(WebSocketConfig.class);

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        log.info("注册 STOMP 端点 >>>>>>>>>>>>>>>>>>>");
        registry.addEndpoint("/ws")
               .setAllowedOrigins("http://localhost:3000")  // 允许前端域名
               .withSockJS();  // 添加 SockJS 支持
        log.info("STOMP 端点注册完成 >>>>>>>>>>>>>>>>>>>");
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        log.info("配置消息代理 >>>>>>>>>>>>>>>>>>>");
        
        // 启用简单消息代理，并配置心跳
        config.enableSimpleBroker("/queue", "/topic")
              .setHeartbeatValue(new long[]{5000, 5000})
              .setTaskScheduler(taskScheduler());
        
        config.setApplicationDestinationPrefixes("/app");
        config.setUserDestinationPrefix("/user");
        
        log.info("WebSocket配置完成 >>>>>>>>>>>>>>>>>>>");
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        // 配置 WebSocket 入站通道
        log.info("配置 WebSocket 入站通道");
        // 添加拦截器
        registration.interceptors(webSocketAuthInterceptor)
            // 添加自定义拦截器
            .interceptors(new ChannelInterceptor() {
                // 在发送消息之前执行
                @Override
                public Message<?> preSend(Message<?> message, MessageChannel channel) {
                    // 获取消息头
                    StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                    // 如果消息头不为空且命令为 SEND
                    if (accessor != null && StompCommand.SEND.equals(accessor.getCommand())) {
                        // 打印收到消息
                        log.info("收到消息: {}", message);
                    }
                    // 返回消息
                    return message;
                }

                // 在发送消息之后执行
                @Override
                public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
                    // 获取消息头
                    StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                    // 如果消息头不为空且命令为 SEND
                    if (accessor != null && StompCommand.SEND.equals(accessor.getCommand())) {
                        // 打印消息发送完成
                        log.info("消息发送完成: {}, 发送状态: {}", message, sent);
                    }
                }
            })
            // 设置任务执行器
            .taskExecutor()
            // 设置核心线程数
            .corePoolSize(4)
            // 设置最大线程数
            .maxPoolSize(8);
    }

    @Override
    public void configureClientOutboundChannel(ChannelRegistration registration) {
        // 配置客户端出站通道
        registration.taskExecutor()
            // 设置核心线程数为4
            .corePoolSize(4)
            // 设置最大线程数为8
            .maxPoolSize(8);
    }

    @Override
    public void configureWebSocketTransport(WebSocketTransportRegistration registry) {
        // 设置消息大小限制为64KB
        registry.setMessageSizeLimit(64 * 1024)
                // 设置发送时间限制为5秒
                .setSendTimeLimit(5 * 1000)
                // 设置发送缓冲区大小限制为256KB
                .setSendBufferSizeLimit(256 * 1024);
    }

    // 创建一个TaskScheduler类型的Bean
    @Bean
    public TaskScheduler taskScheduler() {
        // 创建一个ThreadPoolTaskScheduler对象
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        // 设置线程池大小为1
        scheduler.setPoolSize(1);
        // 设置线程名称前缀
        scheduler.setThreadNamePrefix("websocket-heartbeat-thread-");
        // 初始化线程池
        scheduler.initialize();
        // 返回线程池
        return scheduler;
    }
}